package com.shanjupay.merchant.common.intercept;


import com.shanjupay.common.domain.BusinessException;
import com.shanjupay.common.domain.CommonErrorCode;
import com.shanjupay.common.domain.ErrorCode;
import com.shanjupay.common.domain.RestErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
* 自定义异常处理器
*ControllerAdvice和ExceptionHandler注解实现全局异常处理
*
* */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    private static  final Logger  LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    //捕获异常的处理方法
    @ExceptionHandler(value = Exception.class)//配置ControllerAdvice一起使用实现全局异常处理
    @ResponseBody  //将捕获的异常进行json串返回给前端
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //捕获500异常
    public RestErrorResponse processExcetion(HttpServletRequest request,
                                             HttpServletResponse response,
                                             Exception e){

     //1捕获异常两大分支，自定义BusinessException异常和系统抛出异常
        //1.1如果是自定义异常
        if(e instanceof BusinessException){
            //打印日志 自定义异常
            LOGGER.info(e.getMessage(),e);
            BusinessException businessException = (BusinessException)e;
            //获取里面异常状态码
            ErrorCode errorCode = businessException.getErrorCode();
            return new RestErrorResponse(String.valueOf(errorCode.getCode()),errorCode.getDesc());
        }
        //系统异常
        LOGGER.error("系统异常:",e);
        return new RestErrorResponse(CommonErrorCode.UNKNOWN.getDesc(),String.valueOf(CommonErrorCode.UNKNOWN.getCode()));


    }




}
